<template>
  <!-- 不能在最外层盒子直接设置单击事件，会触发冒泡，子盒子也会触发事件 -->
  <div class="login_modal">
    <!-- 同级盒子不会触发冒泡 -->
    <div class="login_modal_color" @click="hideLogin"></div>
    <div class="login_content">
      <img @click="hideLogin" src="../assets/images/login/userArrow.png" alt="" />
      <ul>
        <li :class="loginWay === 'phone'?'active':''" @click="getPhoneWay">手机号码登录</li>
        <li :class="loginWay === 'wechat'?'active':''" @click="getWechatWay">微信扫码登录</li>
      </ul>
      <section class="form" v-show="loginWay === 'phone'">
        <div class="ipt">
          <input type="number" v-model="phoneNum" placeholder="请输入手机号" />
        </div>
        <slide-verify :l="42" :r="20" :w="362" :h="140" @success="onSuccess" @fail="onFail" @refresh="onRefresh" :style="{ width: '100%' }" class="slide-box" ref="slideBlock" :slider-text="msg"></slide-verify>
        <div class="ipt">
          <input type="text" v-model="test_code" placeholder="请输入短信验证码" />
          <button class="get_value" v-show="getCodestatu" @click="getCodeFn">获取验证码</button>
          <span class="count_dre" v-show="!getCodestatu">{{ count }} s</span>
        </div>
        <div class="ipt">
          <button @click="submitFn">登录</button>
        </div>
      </section>
      <div id="weixin"  v-show="loginWay === 'wechat'"></div>
    </div>
  </div>
</template>

<script>
import { validateTelephone } from '../utils/index.js'
import { SendCodeApi } from '../request/api.js'
import { PhoneLoginApi } from '../request/api.js'
import { CodeLoginApi } from '../request/api.js'
export default {
  data() {
    return {
      msg: '向右滑动',
      phoneNum: '',
      count: 60,
      getCodestatu: true,
      test_code: '',
      loginWay:'phone'
    }
  },
  methods: {
    getPhoneWay(){
      this.loginWay = 'phone'
    },
    getWechatWay(){
      this.loginWay = 'wechat'
      let _this = this;
    new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d",  // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(window.btoa(process.env.VUE_APP_STATE_URL + _this.$route.path)),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9DQo=",
    });
    },
    hideLogin() {
      this.$store.commit('hideModalFn')
    },
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1)
      this.msg = 'login success, 耗时 ' + ms + 's'
    },
    // 拼图失败
    onFail() {
      this.onRefresh() // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = '再试一次'
    },
    // 点击登录按钮
    submitFn(formName) {
      //return的作用是代码不往后执行
      //手机号输入验证
      if (!validateTelephone(this.phoneNum)) {
        
        this.$store.dispatch('changeToastAsync',{
        msg:'手机号输入错误',
        type:'danger'
      })
        return
      }
      //验证码是否输入
      if (this.test_code.trim() === '') {
        
        this.$store.dispatch('changeToastAsync',{
        msg:'请输入验证码',
        type:'danger'
      })
        return
      }
      //判断滑块是否移动
      if (this.msg == '再试一次' || this.msg == '向右滑动') {
        this.$store.dispatch('changeToastAsync',{
        msg:'请滑动滑块',
        type:'danger'
      })
        return
      }
      CodeLoginApi({
        phone: this.phoneNum,
        verifyCode: this.test_code,
      }).then((res) => {
        
        if(res.code === 0 ){
            this.$store.dispatch('changeToastAsync',{
              msg:'登录成功',
             type:'success'
      })
            //设置token
            localStorage.setItem("x-auth-token",res["x-auth-token"])
            //隐藏登录框
            this.$store.commit('hideModalFn')
            //获取登录状态token
            this.$store.commit('changeIsLogined')
            //刷新页面重新加载header组件
            this.$router.go(0)
        } else {
          alert('登陆失败')
        }
      
      })
    },
    getCodeFn() {
      //正则校验手机号
      let result = validateTelephone(this.phoneNum)
      if (result) {
        //手机号输入成功
        SendCodeApi({
          phone: this.phoneNum.trim(),
        })
          .then((res) => {
            //成功
            if (res.code === 0) {
              this.getCodestatu = false
              let timer = null
              this.$store.dispatch('changeToastAsync',{
                   msg:'验证码已发送',
                    type:'success'
      })
              timer = setInterval(() => {
                this.count--
                if (this.count === 0) {
                  this.count = 60
                  this.getCodestatu = true
                  clearInterval(timer)
                }
              }, 1000)
            } else {
              alert(res.message)
              this.$store.dispatch('changeToastAsync',{
               msg:res.message,
                  type:'info'
      })
            }
          })
          .catch((err) => {
             this.$store.dispatch('changeToastAsync',{
               msg:'请重新输入手机号',
                  type:'danger'
      })
          })
      } else {
        alert('请输入手机号')
         this.$store.dispatch('changeToastAsync',{
               msg:'请重新输入手机号',
                  type:'danger'
      })
      }
    },
  },
}
</script>

<style lang="less" scoped>
.login_modal {
  //设置登录页面颜色灰色
  top: 0;
  position: fixed;
  width: 100%;
  height: 100%;

  .login_modal_color {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login_content {
    //设置存放图片的父盒子高度宽度
    width: 555px;
    height: 423px;
    background: url('../assets/images/login/loginBg.png');
    //实现盒子在页面水平垂直居中
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    //使微信盒子居中，必须设置宽度才可使用marginauto
    #weixin{
      width: 300px;
      margin:  0 auto;
    }
    img {
      //定位关闭小图片
      position: absolute;
      right: 60px;
      top: 10px;
    }
    ul {
      display: flex;
      justify-content: center;
      margin-top: 50px;
      li {
        cursor: pointer;
        color: #999;
        &:first-child {
          border-right: solid 1px darkgray;
          padding-right: 10px;
        }
        &:nth-child(2) {
          padding-left: 10px;
        }
      
      }
        .active{
          color: #333;
        }
    }
    .form {
      width: 362px;
      margin: auto;
      .ipt {
        width: 362px;
        height: 50px;
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        input {
          box-sizing: border-box;
          flex: 1;
          text-indent: 1em;
          border: solid 1px #ccc;
        }
        .get_value {
          width: 100px;
          height: 50px;
          color: #fff;
          background: #0a328e;
        }
        .count_dre {
          width: 100px;
          height: 50px;
          color: #fff;
          background: #0a328e;
          text-align: center;
          line-height: 50px;
        }
        button {
          flex: 1;
          background: #0a328e;
          color: #fff;
        }
      }
    }
  }
  /deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
      position: absolute;
      left: 0;
      top: -140px;
      display: none;
      width: 100%;
      box-sizing: border-box;
    }
    .slide-verify-block {
      width: 85px;
      height: 136px;
    }
    .slide-verify-refresh-icon {
      top: -140px;
      display: none;
    }
    &:hover {
      canvas {
        display: block;
      }
      .slide-verify-refresh-icon {
        display: block;
      }
    }
  }
}
</style>
